package com.breeze.leetcode.swordoffer;

/**
 * https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
 * 剑指 Offer 15. 二进制中1的个数
 * <p>
 * 请实现一个函数，输入一个整数（以二进制串形式），输出该数二进制表示中 1 的个数。例如，把 9 表示成二进制是 1001，有 2 位是 1。因此，如果输入 9，则该函数输出 2。
 */
public class Offer15 {
    /**
     * 方法一: 逐位判断
     */
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;
            n = n >>> 1;
        }
        return count;
    }

    /**
     * 方法二: 巧用 n & (n-1)
     */
    public int hammingWeight2(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        Offer15 offer15 = new Offer15();
        System.out.println(offer15.hammingWeight(-1));
        System.out.println(offer15.hammingWeight(0));
        System.out.println(offer15.hammingWeight(5));
        System.out.println(offer15.hammingWeight2(-1));
        System.out.println(offer15.hammingWeight2(0));
        System.out.println(offer15.hammingWeight2(5));
    }
}
